package com.okyai.qa.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.okyai.common.core.text.Convert;
import com.okyai.common.utils.DateUtils;
import com.okyai.common.utils.StringUtils;
import com.okyai.qa.domain.NotesRecord;
import com.okyai.qa.domain.Questionnaire;
import com.okyai.qa.domain.QuestionnaireAnswers;
import com.okyai.qa.domain.QuestionnaireQuestions;
import com.okyai.qa.domain.vo.AnswerDiv;
import com.okyai.qa.domain.vo.AnswerGroupDiv;
import com.okyai.qa.domain.vo.QuestionDiv;
import com.okyai.qa.domain.vo.QuestionEnum;
import com.okyai.qa.mapper.NotesRecordMapper;
import com.okyai.qa.mapper.QuestionnaireMapper;
import com.okyai.qa.service.IQuestionnaireService;

/**
 * 问卷Service业务层处理
 * 
 * @author okyai
 * @date 2021-03-16
 */
@Service
public class QuestionnaireServiceImpl implements IQuestionnaireService 
{
    @Autowired
    private QuestionnaireMapper questionnaireMapper;
    
    @Autowired
    private NotesRecordMapper notesRecordMapper;

    /**
     * 查询问卷
     * 
     * @param questionnaireId 问卷ID
     * @return 问卷
     */
    @Override
    public Questionnaire selectQuestionnaireById(Long questionnaireId)
    {
        return questionnaireMapper.selectQuestionnaireById(questionnaireId);
    }

    /**
     * 查询问卷列表
     * 
     * @param questionnaire 问卷
     * @return 问卷
     */
    @Override
    public List<Questionnaire> selectQuestionnaireList(Questionnaire questionnaire)
    {
        return questionnaireMapper.selectQuestionnaireList(questionnaire);
    }

    /**
     * 新增问卷
     * 
     * @param questionnaire 问卷
     * @return 结果
     */
    @Transactional
    @Override
    public int insertQuestionnaire(Questionnaire questionnaire)
    {
        questionnaire.setCreateTime(DateUtils.getNowDate());
        int rows = questionnaireMapper.insertQuestionnaire(questionnaire);
        insertQuestionnaireQuestions(questionnaire);
        return rows;
    }

    /**
     * 修改问卷
     * 
     * @param questionnaire 问卷
     * @return 结果
     */
    @Transactional
    @Override
    public int updateQuestionnaire(Questionnaire questionnaire)
    {
        questionnaire.setUpdateTime(DateUtils.getNowDate());
        questionnaireMapper.deleteQuestionnaireQuestionsByQuestionnaireId(questionnaire.getQuestionnaireId());
        insertQuestionnaireQuestions(questionnaire);
        return questionnaireMapper.updateQuestionnaire(questionnaire);
    }

    /**
     * 删除问卷对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteQuestionnaireByIds(String ids)
    {
        questionnaireMapper.deleteQuestionnaireQuestionsByQuestionnaireIds(Convert.toStrArray(ids));
        return questionnaireMapper.deleteQuestionnaireByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除问卷信息
     * 
     * @param questionnaireId 问卷ID
     * @return 结果
     */
    @Override
    public int deleteQuestionnaireById(Long questionnaireId)
    {
        questionnaireMapper.deleteQuestionnaireQuestionsByQuestionnaireId(questionnaireId);
        return questionnaireMapper.deleteQuestionnaireById(questionnaireId);
    }

    /**
     * 新增问卷题目信息
     * 
     * @param questionnaire 问卷对象
     */
    public void insertQuestionnaireQuestions(Questionnaire questionnaire)
    {
        List<QuestionnaireQuestions> questionnaireQuestionsList = questionnaire.getQuestionnaireQuestionsList();
        Long questionnaireId = questionnaire.getQuestionnaireId();
        if (StringUtils.isNotNull(questionnaireQuestionsList))
        {
            List<QuestionnaireQuestions> list = new ArrayList<QuestionnaireQuestions>();
            for (QuestionnaireQuestions questionnaireQuestions : questionnaireQuestionsList)
            {
                questionnaireQuestions.setQuestionnaireId(questionnaireId);
                list.add(questionnaireQuestions);
            }
            if (list.size() > 0)
            {
                questionnaireMapper.batchQuestionnaireQuestions(list);
            }
        }
    }

	@Override
	public Questionnaire preview(Long questionnaireId) {
		Questionnaire questionnaire = questionnaireMapper.selectQuestionnaireById(questionnaireId);
		List<QuestionnaireQuestions> questions = questionnaire.getQuestionnaireQuestionsList();
		
		List<QuestionDiv> divList = new ArrayList<>();
		if(questions.size()>0) {
			questions.stream().forEach(q->{
				QuestionDiv qd = answerTransform(q,new ArrayList<NotesRecord>());
				divList.add(qd);
			});
		}
		questionnaire.setQuestions(divList);
		return questionnaire;
	}
	
	@Override
	public Questionnaire questionnaireInfo(Long questionnaireId, Long notesId) {
		Questionnaire questionnaire = questionnaireMapper.selectQuestionnaireById(questionnaireId);
		List<QuestionnaireQuestions> questions = questionnaire.getQuestionnaireQuestionsList();
		if(notesId==null) {
			notesId = -1l;
		}
		NotesRecord notesRecord = new NotesRecord();
		notesRecord.setNotesId(notesId);
		List<NotesRecord> records = notesRecordMapper.selectNotesRecordList(notesRecord);
		
		List<QuestionDiv> divList = new ArrayList<>();
		if(questions.size()>0) {
			questions.stream().forEach(q->{
				QuestionDiv qd = answerTransform(q,records);
				divList.add(qd);
			});
		}
		questionnaire.setQuestions(divList);
		return questionnaire;
	}

	private QuestionDiv answerTransform(QuestionnaireQuestions question,List<NotesRecord> records){
		QuestionDiv returnDiv = new QuestionDiv();
		returnDiv.setNo(question.getQuestionsIndex());
		returnDiv.setShowStyle(question.getShowStyle());
		returnDiv.setShowType(question.getShowType());
		returnDiv.setTitle(question.getTitle());
		
		List<QuestionnaireAnswers> list = JSON.parseArray(question.getAnswer(), QuestionnaireAnswers.class);
				
		//单选题和判断题
		if(QuestionEnum.TYPE_DXT.getType().equals(question.getQuestionsType())
				||QuestionEnum.TYPE_PDT.getType().equals(question.getQuestionsType())){
			returnDiv.setIsGroup(false);
			//每个题目就是一个对象，最简单
			
			list.stream().forEach(a->{
				AnswerDiv ans = new AnswerDiv();
				ans.setLabel(a.getAnswerText());
				ans.setWidth("col-sm-12");
				//name 的规则 考卷ID_考题ID_选项序号
				String inputName = question.getQuestionnaireId()+"_"+question.getQuestionsId();
				StringBuffer input = new StringBuffer("<input type='radio' name='a_");
				input.append(inputName).append("' value='").append(a.getAnswerText()).append("' ");
				NotesRecord nr = getNotesRecord(inputName,a.getAnswerText(),records);
				if(nr!=null) {
					input.append(" checked ");
				}
				input.append(" >&nbsp;").append(a.getAnswerText());
				ans.setAnswerInput(input.toString());
				ans.setInputRemark(a.getRemark());
				returnDiv.getAnswer().add(ans);
			});
		}else if(QuestionEnum.TYPE_DXZ.getType().equals(question.getQuestionsType())||QuestionEnum.TYPE_PDZ.getType().equals(question.getQuestionsType())){
			returnDiv.setIsGroup(true);
			//设置组头
			String[] ts = question.getTitleGroup().split("\\|");
			String[] group = new String[ts.length+1];
			group[0] = "";
			if(QuestionEnum.TYPE_PDZ.getType().equals(question.getQuestionsType())) {
				group[0] = returnDiv.getTitle();
			}
			for(int i=0;i<ts.length;i++) {
				group[i+1] = ts[i];
			}
			//开始设置值
			for(int i=0;i<group.length;i++) {
				AnswerGroupDiv gr = new AnswerGroupDiv();
				gr.setNo(i);
				gr.setLabel(group[i]);
				
				
				int asize=12/((ts.length>0?1:0)+list.size());
				gr.setWidth("col-sm-"+(12-asize*list.size()));
				
				if(ts.length<2) {
					gr.setWidth("hidden");
				}
				//计算宽度
				for(QuestionnaireAnswers a:list) {
					AnswerDiv ans = new AnswerDiv(i,a.getAnswerText());
					ans.setWidth("col-sm-"+asize);
					if(QuestionEnum.TYPE_PDZ.getType().equals(question.getQuestionsType())) {
						gr.setWidth("col-sm-10");
						ans.setWidth("col-sm-1");
					}
					if(i>0) {
						ans.setLabel(a.getAnswerText());
						String inputName = question.getQuestionnaireId()+"_"+question.getQuestionsId()+"_"+i;
						StringBuffer input = new StringBuffer("<input type='radio' name='a_");
						String value = gr.getLabel()+" "+a.getAnswerText();
						input.append(inputName).append("' value='").append(value).append("' ");
						NotesRecord nr = getNotesRecord(inputName,value,records);
						if(nr!=null) {
							input.append(" checked ");
						}
						input.append(" >");
						ans.setAnswerInput(input.toString());
						ans.setInputRemark(a.getRemark());
					}
					gr.getAnswer().add(ans);
				}
				returnDiv.getGroup().add(gr);
			}
		}else if(QuestionEnum.TYPE_FXT.getType().equals(question.getQuestionsType())) {
			returnDiv.setIsGroup(false);
			//每个题目就是一个对象，最简单
			list.stream().forEach(a->{
				AnswerDiv ans = new AnswerDiv();
				ans.setLabel(a.getAnswerText());
				ans.setWidth("col-sm-12");
				//name 的规则 考卷ID_考题ID_选项序号
				String inputName = question.getQuestionnaireId()+"_"+question.getQuestionsId()+"_"+a.getIndex();
				StringBuffer input = new StringBuffer("<input type='checkbox' name='a_");
				input.append(inputName).append("' value='").append(a.getAnswerText()).append("' ");
				NotesRecord nr = getNotesRecord(inputName,a.getAnswerText(),records);
				if(nr!=null) {
					input.append(" checked ");
				}
				input.append(" >&nbsp;").append(a.getAnswerText());
				ans.setAnswerInput(input.toString());
				ans.setInputRemark(a.getRemark());
				returnDiv.getAnswer().add(ans);
			});
		}else if(QuestionEnum.TYPE_TKT.getType().equals(question.getQuestionsType())) {
			returnDiv.setIsGroup(false);
			//填空题
			list.stream().forEach(a->{
				AnswerDiv ans = new AnswerDiv();
				ans.setLabel(a.getAnswerText());
				ans.setWidth("col-sm-12");
				//name 的规则 考卷ID_考题ID_选项序号
				String inputName = question.getQuestionnaireId()+"_"+question.getQuestionsId()+"_"+a.getIndex();
				StringBuffer input = new StringBuffer(a.getAnswerText());
				input.append("&nbsp;<input type='text' name='a_").append(inputName).append("' ");
				NotesRecord nr = getNotesRecord(inputName,null,records);
				if(nr!=null) {
					input.append(" value='").append(nr.getAnswerValue()).append("'");
				}
				if("".equals(a.getInputType())) {
					input.append(" class=''");
				}
				input.append(" >");
				ans.setAnswerInput(input.toString());
				ans.setInputRemark(a.getRemark());
				returnDiv.getAnswer().add(ans);
			});
		}
		return returnDiv;
	}
	
	private NotesRecord getNotesRecord(String name,String value,List<NotesRecord> list) {
		if(list.size()>0) {
			for(NotesRecord nr:list) {
				if(value==null) {
					if(nr.getAnswerName().equals("a_"+name)) {
						return nr;
					}
				}else {
					if(nr.getAnswerName().equals("a_"+name)&&nr.getAnswerValue().equals(value)) {
						return nr;
					}
				}
				
			}
		}
		return null;
	}
}
